import Router from "koa-router";

import { ObjectId } from "mongodb";

import { PERFIX_URL } from "@/config/router";

import fs from "fs";

const KoaRouter = new Router();
KoaRouter.prefix(`${PERFIX_URL}/user`);

// 存储
KoaRouter.post("/file", async (ctx) => {
  // @ts-ignore
  const file: File = await ctx.request.files.file;
  const write = global.gfs.createWriteStream({
    filename: file.name,
    content_type: file.type,
  });
  // @ts-ignore
  const res = await fs.createReadStream(file.path).pipe(write);
  ctx.body = {
    id: res.id,
  };
});

// 查找通过base64返回
KoaRouter.get("/findFile", async (ctx) => {
  const { _id } = ctx.query;
  const res = await findFile(_id.toString());
  ctx.body = res
});

function findFile(_id: string) {
  return new Promise(async (resolve) => {
    // 对应数据库插件新建fs.files的表集合查找出文件的信息
    const res = await global.gfs.files.find({ _id: new ObjectId(_id) }).toArray();
    let arr: any = [];
    // 对应数据库插件新建fs.chunks的表集合查找出的文件内容
    const read = global.gfs.createReadStream({ _id: res[0]._id });
    read.on("data", (data: any) => {
      arr.push(data);
    });
    read.on("end", () => {
      arr = `data:${res[0].contentType};base64,${Buffer.from(
        Buffer.concat(arr)
      ).toString("base64")}`;
      resolve({ arr, type: res[0].contentType, name: res[0].filename });
    });
  });
}

// 查询是否存在
KoaRouter.get("/fileExist", async (ctx) => {
  const { _id } = ctx.query;
  const res = await fileExist(_id.toString());
  ctx.body = {
    isExist: res,
  };
});

function fileExist(_id: string) {
  return new Promise((resolve, reject) => {
    global.gfs.exist({ _id }, (err: any, res: unknown) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  });
}

// 删除文件
KoaRouter.delete("/fileDelete", async (ctx) => {
  const { _id } = ctx.query;
  let res;
  const exist = await fileExist(_id.toString());
  if (exist) {
    res = await fileDelete(_id.toString());
  }
  ctx.body = {
    message: res ? "删除成功" : "没有这个文件",
  };
});

function fileDelete(_id: string) {
  return new Promise((resolve, reject) => {
    global.gfs.remove({ _id }, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve(true);
      }
    });
  });
}

export default KoaRouter;
